package com.niiwoo.civet.user.service.local;

import com.niiwoo.civet.user.dao.entity.MobileIdentity;
import com.niiwoo.civet.user.dao.mapper.MobileIdentityMapperExt;
import com.niiwoo.civet.user.dto.MobileIdentityInfoDTO;
import com.niiwoo.civet.user.dto.response.MobileIdentityDTO;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.base.utils.SecurityUtil;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户（手机号+身份证号）MD5字符串与userId映射
 * Created by dell on 2017/12/5.
 * Description：civet-parent
 */
@Slf4j
@Service
public class MobileIdentityService {

    @Autowired
    private PrivacyMasks privacyMasks;
    @Autowired
    private MobileIdentityMapperExt mobileIdentityMapperExt;

    @Transactional
    public int insertMappingData(String userId){
        MobileIdentityInfoDTO mobileIdentityInfoDTO = mobileIdentityMapperExt.queryMobileAndIdentity(userId);
        StringBuffer sb = new StringBuffer();
        sb.append(privacyMasks.decryptPrivacy(mobileIdentityInfoDTO.getMobileNo()));
        sb.append(privacyMasks.decryptPrivacy(mobileIdentityInfoDTO.getIdCard()));
        String mobileIdentity = SecurityUtil.MD5(sb.toString());

        MobileIdentity model = mobileIdentityMapperExt.selectByPrimaryKey(mobileIdentity);
        if (model==null){
            model = new MobileIdentity();
            model.setMobileIdentity(mobileIdentity);
            model.setUserId(userId);
            model.setCreateTime(new Date());
            return mobileIdentityMapperExt.insertSelective(model);
        }
        return 0;
    }


    /**
     * 查询映射用户
     * @param mobileIdentity md5加密字符串
     * @return
     */
    public MobileIdentityDTO queryMobileIdentity(String mobileIdentity){
        MobileIdentity model = mobileIdentityMapperExt.selectByPrimaryKey(mobileIdentity);
        if (model!=null){
            MobileIdentityDTO mobileIdentityDTO = new MobileIdentityDTO();
            BeanUtils.copyProperties(model, mobileIdentityDTO);
            return mobileIdentityDTO;
        }
        return null;
    }

}
